package net.zoneland.zrdp.framework.interceptor;

import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;

import net.zoneland.zrdp.common.annotation.RepeatSubmit;
import net.zoneland.zrdp.common.core.domain.AjaxResult;
import net.zoneland.zrdp.common.utils.JacksonUtils;
import net.zoneland.zrdp.common.utils.ServletUtils;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 防止重复提交拦截器
 *
 * @author zonevue
 */
@Component
public abstract class RepeatSubmitInterceptor implements HandlerInterceptor
{
    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception
    {
        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Method method = handlerMethod.getMethod();
            final RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
            if (annotation != null && (this.isRepeatSubmit(request, annotation))) {
                final AjaxResult ajaxResult = AjaxResult.error(annotation.message());
                ServletUtils.renderString(response, JacksonUtils.toJsonString(ajaxResult));
                return false;
            }
        }
        return true;
    }

    /**
     * 验证是否重复提交由子类实现具体的防重复提交的规则
     */
    public abstract boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation) throws JsonProcessingException;
}
